﻿using S.EarTag.Domain.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using SqlSugar.Extensions;

namespace S.EarTag.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        private readonly SqlSugarClient _db;
        public BaseRepository(SqlSugarClient db)
        {
            _db = db;
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> AddAsync(T entity)
        {
            var result=await _db.Insertable(entity).ExecuteReturnIdentityAsync();
            return result.ObjToBool();
        }
        /// <summary>
        /// 根据Id进行删除
        /// </summary>
        /// <param name="id">要删除数据的Id</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> DeleteAsync(int id)
        {
            var result = await _db.Deleteable<T>().In(id).ExecuteCommandAsync();
            return result.ObjToBool();
        }
        /// <summary>
        /// 查询表全部数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAllAsync()
        {
            return await _db.Queryable<T>().ToListAsync();
        }
        /// <summary>
        /// 根据主键Id进行查询数据用于反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetByIdAsync(int id)
        {
            return await _db.Queryable<T>().InSingleAsync(id);
            //return await _db.Queryable<T>(id)
        }
        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(T entity)
        {
            var result = await _db.Updateable(entity).ExecuteCommandAsync();
            return result.ObjToBool();
        }
    }
}
